

import { Ast, createRootAst, uploadXml } from "./ast";
import { BaseVisitor } from "./core";

class ScanDialogContext {
    cancel: Function;
    hasDialog: boolean;
}

class ScanDialogVisitor extends BaseVisitor {
    private getLv(node: Ast) {
        return node.bounds.top / device.height;
    }
    lvMinNode: Ast;
    private getLvMin(node: Ast, min: number = 0.1) {
        if (this.getLv(node) > min) {
            this.lvMinNode = node;
            return;
        }
        node.children.find(c => this.getLvMin(c, min))
        return
    }
    private i: number = 0;
    visitFrameLayout(node: Ast, ctx: ScanDialogContext) {
        // 顶级frame
        if (!node.parent) {
            const { left, right, top, bottom } = node.bounds;
            ctx.hasDialog = top > 0;
            if (ctx.hasDialog) {
                this.getLvMin(node)
                if (this.lvMinNode) {
                    const { left, right, top, bottom } = this.lvMinNode.bounds;
                    const x = (left + right) / 2;
                    const y = (top + 0) / 2;
                    this.i += 1;
                    uploadXml(`roomInfo`, `dialog_${this.i}`)
                    events.broadcast.emit('UPDATE', `发现弹框:dialog_${this.i}`)
                    if(x > 0 && y > 0){
                        ctx.cancel = () => click(x, y);
                    }
                } else {
                    ctx.cancel = () => back();
                }
            }
        }
        node.children.map(c => c.visit(this, ctx))
    }
}

export function scanDialogOnce() {
    let ctx = new ScanDialogContext()
    const visitior = new ScanDialogVisitor()
    const root = createRootAst()
    root.visit(visitior, ctx);
    if (ctx.cancel) {
        ctx.cancel()
    }
    return ctx;
}

export function scanDialog(stop: () => boolean) {
    let ctx = new ScanDialogContext()
    const visitior = new ScanDialogVisitor()
    const root = createRootAst()
    root.visit(visitior, ctx);
    while (ctx.hasDialog && stop()) {
        ctx.cancel && ctx.cancel()
        sleep(1000)
        ctx = new ScanDialogContext()
        const root = createRootAst()
        root.visit(visitior, ctx);
    }
    return ctx;
}
